package com.student_exam_system.Filter;

import com.student_exam_system.Util.JwtUtil;
import com.student_exam_system.Util.SimpleCache;
import com.student_exam_system.pojo.LoginUser;
import com.student_exam_system.pojo.Result;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author fire'ge
 */
@Component
public class JWTFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        if (token==null){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //验证token
        int jwtUserId = JwtUtil.getJWTUserId(token);
        SimpleCache cache = SimpleCache.getInstance();
        Map<String, Object> cacheMap = cache.getCacheMap();
        System.out.println(cacheMap);
        LoginUser loginUser = (LoginUser)cacheMap.get("login" + jwtUserId);
        if (loginUser==null){
            httpServletResponse.setContentType("application/json;charset:utf-8");
            httpServletResponse.getWriter().println(Result.fail("用户未登录"));
            return;
        }
        //放入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
